﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Text.RegularExpressions;

using System.ComponentModel;


namespace AppCommerciaux.Views
{
    /// <summary>
    /// Logique d'interaction pour ConsulterClientView.xaml
    /// </summary>
    public partial class ConsulterClientView : UserControl
    {
        // Classe pour le tri des colonnes de la listView
        public class SortAdorner : Adorner
        {
            private static Geometry ascGeometry =
                    Geometry.Parse("M 0 4 L 3.5 0 L 7 4 Z");

            private static Geometry descGeometry =
                    Geometry.Parse("M 0 0 L 3.5 4 L 7 0 Z");

            public ListSortDirection Direction { get; private set; }

            public SortAdorner(UIElement element, ListSortDirection dir)
                : base(element)
            {
                this.Direction = dir;
            }

            protected override void OnRender(DrawingContext drawingContext)
            {
                base.OnRender(drawingContext);

                if (AdornedElement.RenderSize.Width < 20)
                    return;

                TranslateTransform transform = new TranslateTransform
                        (
                                AdornedElement.RenderSize.Width - 15,
                                (AdornedElement.RenderSize.Height - 5) / 2
                        );
                drawingContext.PushTransform(transform);

                Geometry geometry = ascGeometry;
                if (this.Direction == ListSortDirection.Descending)
                    geometry = descGeometry;
                drawingContext.DrawGeometry(Brushes.Black, null, geometry);

                drawingContext.Pop();
            }
        }

        // Variable pour le tri des colonnes de la listView
        private GridViewColumnHeader listViewSortCol = null;
        private SortAdorner listViewSortAdorner = null;

        private List<Entity.tiers_societe> allClients = null;

        private List<TextBox> textBoxError = null;
        private List<TextBox> allTextBoxValid = new List<TextBox>();


        public ConsulterClientView()
        {
            InitializeComponent();

            allTextBoxValid.Add(textBoxTel);
            allTextBoxValid.Add(textBoxFax);
            allTextBoxValid.Add(textBoxSiret);
            allTextBoxValid.Add(textBoxCp);
            allTextBoxValid.Add(textBoxRaisonSociale);
            allTextBoxValid.Add(textBoxRue);
            allTextBoxValid.Add(textBoxVille);

            using (Entity.liv3Entities1 dc = new Entity.liv3Entities1())
            {
                var querySelect = from tiers_societe in dc.tiers_societe
                                  select tiers_societe;

                allClients = querySelect.ToList();
                listViewClient.ItemsSource = allClients;
            }
        }

        private void buttonModification_Click(object sender, RoutedEventArgs e)
        {

            initialisationFormatTextBox();

            List<TextBox> textBoxError = validAll();

            if (textBoxError.Count == 0)
            {
                using (Entity.liv3Entities1 dc = new Entity.liv3Entities1())
                {
                    var oneClient = (Entity.tiers_societe)listViewClient.SelectedItem;
                    var querySelect = from tiers_societe in dc.tiers_societe
                                      where tiers_societe.id == oneClient.id
                                      select tiers_societe;

                    oneClient = querySelect.FirstOrDefault();

                    if (oneClient != null)
                    {
                        oneClient.ville = textBoxVille.Text;
                        oneClient.rue = textBoxRue.Text;
                        oneClient.cp = textBoxCp.Text;
                        oneClient.fax = textBoxFax.Text;
                        oneClient.tel = textBoxTel.Text;
                        oneClient.siret = textBoxSiret.Text;
                        oneClient.raisonSociale = textBoxRaisonSociale.Text;
                        oneClient.synchro = "M";

                        dc.SaveChanges();
                        querySelect = from tiers_societe in dc.tiers_societe
                                      select tiers_societe;

                        allClients = querySelect.ToList();

                        listViewClient.ItemsSource = allClients;
                        listViewClient.SelectedItem = oneClient;
                    }
                }
                
            }
            else
            {
                //MessageBox.Show("Veuillez corriger les erreurs de saisie !");
                foreach (TextBox tbx in textBoxError)
                {
                    tbx.Background = Brushes.Tomato;
                }
                textBoxError.First().Focus();
            }

        }

        private void listViewClient_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            textBoxCp.IsEnabled = true;
            textBoxFax.IsEnabled = true;
            textBoxRaisonSociale.IsEnabled = true;
            textBoxRue.IsEnabled = true;
            textBoxSiret.IsEnabled = true;
            textBoxTel.IsEnabled = true;
            textBoxVille.IsEnabled = true;
            buttonModification.IsEnabled = true;

            initialisationFormatTextBox();
            
            if ((Entity.tiers_societe)listViewClient.SelectedItem != null)
            {
                Entity.tiers_societe client = (Entity.tiers_societe)listViewClient.SelectedItem;
                textBoxCp.Text = client.cp.ToString();
                textBoxRaisonSociale.Text = client.raisonSociale.ToString();
                textBoxRue.Text = client.rue.ToString();
                textBoxVille.Text = client.ville.ToString();
                textBoxFax.Text = client.fax.ToString();
                textBoxTel.Text = client.tel.ToString();
                textBoxSiret.Text = client.siret.ToString();
                labelRemise.Content = client.remise.ToString() + " %";
            }
        }

        private void listViewColumnHeader_Click(object sender, RoutedEventArgs e)
        {
            GridViewColumnHeader column = (sender as GridViewColumnHeader);
            string sortBy = column.Tag.ToString();
            if (listViewSortCol != null)
            {
                AdornerLayer.GetAdornerLayer(listViewSortCol).Remove(listViewSortAdorner);
                listViewClient.Items.SortDescriptions.Clear();
            }

            ListSortDirection newDir = ListSortDirection.Ascending;
            if (listViewSortCol == column && listViewSortAdorner.Direction == newDir)
                newDir = ListSortDirection.Descending;

            listViewSortCol = column;
            listViewSortAdorner = new SortAdorner(listViewSortCol, newDir);
            AdornerLayer.GetAdornerLayer(listViewSortCol).Add(listViewSortAdorner);
            listViewClient.Items.SortDescriptions.Add(new SortDescription(sortBy, newDir));
        }



        private List<TextBox> validAll()
        {

            textBoxError = new List<TextBox>();

            if (validNbCarNtoM(textBoxRaisonSociale, 1, 50) == false)
            {
                textBoxError.Add(textBoxRaisonSociale);
            }
            if (validNbCarNtoM(textBoxRue, 1, 50) == false)
            {
                textBoxError.Add(textBoxRue);
            }
            if (validNbChiffre(textBoxCp, 5) == false)
            {
                textBoxError.Add(textBoxCp);
            }
            if (validNbCarNtoM(textBoxVille, 1, 40) == false)
            {
                textBoxError.Add(textBoxVille);
            }
            if (validTel(textBoxTel) == false)
            {
                textBoxError.Add(textBoxTel);
            }
            if (validTel(textBoxFax) == false)
            {
                textBoxError.Add(textBoxFax);
            }
            if (validNbChiffre(textBoxSiret, 15) == false)
            {
                textBoxError.Add(textBoxSiret);
            }

            return textBoxError;
        }

        private bool validNbChiffre(TextBox txbx, int n)
        {
            Boolean wRetour = false;

            Regex r = new Regex(@"^\d{" + n.ToString() + "}");
            Match m = r.Match(txbx.Text.ToString());
            if (m.ToString() == txbx.Text.ToString() && txbx.Text.Length == n)
            {
                wRetour = true;
            }
            else
            {
                txbx.ToolTip = "Champ obligatoire - Longueur obligatoire de " + n.ToString() + " chiffres !";
            }
            return wRetour;
        }

        private bool validNbCarNtoM(TextBox txbx, int n, int q)
        {
            Boolean wRetour = false;
            if (txbx.Text.Length >= n && txbx.Text.Length <= q)
            {
                wRetour = true;
            }
            else
            {
                txbx.ToolTip = "Champ obligatoire - Longueur comprise entre " + n.ToString() + " et " + q.ToString() + " caractères !";
            }
            return wRetour;
        }

        private bool validTel(TextBox txbx)
        {
            Boolean wRetour = false;

            Regex r = new Regex(@"^0\d[ ]*(\d{2})[ ]*(\d{2}) *(\d{2}) *(\d{2})");
            Match m = r.Match(txbx.Text.ToString());
            if (m.ToString() == txbx.Text.ToString() && (txbx.Text.Length == 10 || txbx.Text.Length == 14))
            {
                wRetour = true;
            }
            else
            {
                txbx.ToolTip = "Format de n° invalide => 0123456789 ou 01 23 45 67 89";
            }
            return wRetour;
        }

        private void initialisationFormatTextBox()
        {
            foreach (var item in allTextBoxValid)
            {
                item.Background = Brushes.White;
                item.ToolTip = null;
            }
        }

    }
}
